package wangjg.xuexiban.activity.web;

import java.io.File;

import wangjg.commons.compress.Zip;
import wangjg.xuexiban.R;
import wangjg.xuexiban.activity.BasicActivity;
import wangjg.xuexiban.util.Constant;
import wangjg.xuexiban.util.WebClient;
import wangjg.xuexiban.util.WebClient.Callback;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class WebViewActivity extends BasicActivity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webveiw);
		this.init();
	}
	
	private void init(){
		WebView webView = getWebView();
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		webView.addJavascriptInterface(new External(),"external");
		webView.setWebChromeClient(new WebChromeClient(){
			  public void onProgressChanged(WebView view, int newProgress) {
			  }
		});
		webView.setWebViewClient(new WebViewClient() {
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
				Toast.makeText(WebViewActivity.this, "异常:! " + description, Toast.LENGTH_LONG).show();
			}
		});
		Intent intent = getIntent();
		String url = intent.getStringExtra("url");
		if(url!=null && url.length()!=0){
			webView.clearCache(true);
			webView.loadUrl(url);
		}
	}
	
	class External {
		public void alert(String str){
			Toast toast=Toast.makeText(WebViewActivity.this, str, Toast.LENGTH_SHORT);
			toast.show();
		}
		
		public void install(String id, String fileUrl){
			download(fileUrl, new DownloadCallback(id));
		}

	}
	
	public void download(final String url, final Callback callback) {
		new Thread(){
			public void run(){
				WebClient webClient = new WebClient(Constant.DEFAULT_DATA_ROOT);
				String filePath = webClient._download(url, Constant.DEFAULT_DATA_ROOT);
				callback.handle(filePath);
			}
		}.start();
	}
	
	class DownloadCallback implements WebClient.Callback{
		private String id;
		
		public DownloadCallback(String id){
			this.id=id;
		}
		
		public void handle(String filePath) {
			boolean success = false;
			try {
				if(filePath!=null && filePath.length()>0){
					new Zip().unzip(filePath, Constant.DEFAULT_DATA_ROOT);
					success = true;
				}
			} catch (Exception e) {
				Log.e(this.getClass().getSimpleName(), "解压错误", e);
			}
			boolean b = new File(filePath).delete();
			
			getWebView().loadUrl("javascript:installOver('"+id+"',"+success+");");
		}
	}
	
	private WebView getWebView(){
		WebView webView = (WebView)findViewById(R.id.webView1);
		return webView;
	}
}
